package com.qf.air.service.impl;

import com.qf.air.service.ChartService;
import com.qf.air.util.ElasticsearchUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.InternalOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ASUS
 * @version V1.0
 * @Project air
 * @Package com.qf.air.service.impl
 * @Date 2021/11/5 21:24
 */
@Service
public class ChartServiceImpl implements ChartService {

    @Override
    public List<Map> districtCount() throws IOException {
        SearchRequest request = new SearchRequest("air");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.aggregation(AggregationBuilders.terms("districtCount").field("districtName"));
        builder.size(0);//不需要数据，只需要统计
        request.source(builder);
        SearchResponse resp = ElasticsearchUtil.getClient().search(request, RequestOptions.DEFAULT);
        Terms terms = resp.getAggregations().get("districtCount");
        List<Map> result = new ArrayList<>();
        for (Terms.Bucket bucket : terms.getBuckets()) {
            Map map = new HashMap<>();
            map.put("value",bucket.getDocCount());
            map.put("name",bucket.getKey());
            result.add(map);
        }
        return result;
    }
}
